package com.dhms.vostok1.repository

import com.dhms.vostok1.data.fault.FaultLevel
import com.dhms.vostok1.data.fault.FaultLevelListData
import com.dhms.vostok1.data.fault.FaultTypeItemData
import com.dhms.vostok1.database.fault.FaultDao
import com.dhms.vostok1.service.net.NetworkApi
import kotlinx.coroutines.flow.Flow

class FaultRepository(
    private val faultDao: FaultDao,
) {

    val faultLevel: Flow<List<FaultLevel>> get() = faultDao.getFaultLevel()
    val faultTypes: Flow<List<FaultTypeItemData>> get() = faultDao.getFaultTypes()

    suspend fun updateFaultLevel(): FaultLevelListData {
        val res = NetworkApi.getFaultLevelList()
        val resData = res.getOrNull()?.body()?.data
        val levelList = resData ?: DEFAULT_FAULT_LEVEL_LIST
        faultDao.insertFaultLevel(levelList)

        return levelList
    }

    suspend fun updateFaultTypes(origId: Long): List<FaultTypeItemData>? {
        val query = HashMap<String, Long>()
        query["org_id"] = origId
        val res = NetworkApi.getFaultTypes(query)
        val resData = res.getOrNull()?.body()?.data
        resData?.let {
            faultDao.insertFaultTypes(it)
        }
        return resData
    }

    companion object {

        @Volatile
        private var instance: FaultRepository? = null

        fun getInstance(faultDao: FaultDao) =
            instance ?: synchronized(this) {
                instance ?: FaultRepository(faultDao).also { instance = it }
            }

        val DEFAULT_FAULT_LEVEL_LIST = listOf(
            FaultLevel(
                "#f3b82c",
                "#f3b82c",
                "一般",
                1,
            ),
            FaultLevel(
                "#eb881d",
                "#EA881D",
                "较重",
                2,
            ),
            FaultLevel(
                "#ee4a17",
                "#ee4a17",
                "严重",
                3,
            ),
            FaultLevel(
                "#c60202",
                "#C60203",
                "特别严重",
                4,
            ),
        )

        val DEFAULT_FAULT_LEVEL_COLOR_MAP = mapOf(
            1 to "#BDE4FF",
            2 to "#4CB2FA",
            3 to "#006CB8",
            4 to "#003D68",
        )
    }
}
